<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="新增销售单"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :label-width="formInfo.labelWidth"
          />
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
              >
                <template v-slot:col-qty="scope">
                  <el-input-number
                    v-model.lazy="scope.row.qty"
                    clearable
                    controls-position="right"
                    :precision="0"
                    :min="0"
                    :max="scope.row.purchQty"
                  />
                </template>
                <template v-slot:col-refuseQty="scope">
                  <el-input-number
                    v-model.lazy="scope.row.refuseQty"
                    clearable
                    controls-position="right"
                    :precision="0"
                    :min="0"
                    :max="scope.row.purchQty"
                  />
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>
<script setup name="saleOrderModify">
import {
  addSaleOrder,
  updateSaleOrder,
  saleDetailBySaleId,
  getSaleDetailByPurch,
  getSaleOrderById,
} from '@/api/supplier.js'
import { getPurchOrderDetailAll } from '@/api/purch.js'

import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  pendSaleorderId: {
    type: [Number, String],
  },
  saleOrderId: {
    type: [Number, String],
  },
  purchType: {
    type: [Number, String],
  },
})

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const fullInfo = reactive({
  btnList: [{ label: '提交', event: save, show: true }],
})
let formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '采购单号',
      value: 'purchNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '客户',
      value: 'hospitalName',
      type: 'input',
      disabled: true,
    },
    {
      label: '客户部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '收货地址',
      value: 'receiveAddressValue',
      type: 'input',
      disabled: true,
    },
    {
      label: '联系人',
      value: 'receiveContacts',
      type: 'input',
      disabled: true,
    },
    {
      label: '联系电话',
      value: 'receivePhone',
      type: 'input',
      disabled: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  labelWidth: '120px',
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty' },
    { value: 'refuseQty' },
    { value: 'sumAmount' },
  ],
  fieldList: [
    {
      label: '设备名称',
      value: 'commonName',
    },
    {
      label: '设备编码',
      value: 'productCode',
    },
    {
      label: '设备规格',
      value: 'standard',
    },
    {
      label: '设备品牌',
      value: 'trademark',
    },
    {
      label: '厂家名称',
      value: 'brandName',
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethodAsset,
    },
    {
      label: '销售数量',
      value: 'purchQty',
      type: 'column',
    },
    {
      label: '接收数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
    },
    {
      label: '拒收数量',
      value: 'refuseQty',
      type: 'slot',
      minWidth: '250px',
    },
    {
      label: '销售金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethodAsset,
    },
  ],
})
const orgInfo = reactive({
  visible: false,
})
const formRefs = ref('')
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let sumAmount = proxy.$fn.accMul(row.qty || 0, parseFloat(row.price))
        row['sumAmount'] = sumAmount
      })
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  if (props.pendSaleorderId) {
    getPendMain()
  } else if (props.saleOrderId) {
    getMain()
    getList()
  }
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
})

function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let itemList = tableInfo.data
      .filter(
        (item) => item.purchQty !== proxy.$fn.accAdd(item.qty, item.refuseQty)
      )
      .map((item) => item.commonName)
    if (itemList.length) {
      proxy.$alert(
        `设备【${itemList}】的接收数量与拒绝数量之和不等于销售数量！`,
        '操作提示',
        {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
        }
      )
      return
    }
    tableInfo.data.forEach((item) => {
      item.calcQty = item.qty
      item.refuseCalcQty = item.refuseQty
    })
    formInfo = {
      ...formInfo.data,
      details: tableInfo.data,
    }
    let api = ''
    if (props.pendSaleorderId) {
      api = addSaleOrder
    } else if (props.saleOrderId) {
      api = updateSaleOrder
    }
    api(formInfo).then((resp) => {
      if (resp && resp.success) {
        emit('returnModify')
        showDialog.value = false
      }
    })
  })
}
function openDeptWindow() {
  orgInfo.visible = true
}
function reset() {
  orgInfo.visible = false
}
function getPurchOrderDetailAllList(orderId) {
  getPurchOrderDetailAll({ purchOrderId: orderId }).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}
function getPendMain() {
  let param = {
    id: props.pendSaleorderId,
    purchType: props.purchType,
  }
  getSaleDetailByPurch(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      data.details.forEach((item) => {
        item['qty'] = item.purchQty
        item['refuseQty'] = 0
      })
      tableInfo.data = data.details
      formInfo.data = res.data
    }
  })
}
function getMain() {
  getSaleOrderById(props.saleOrderId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
    }
  })
}
function getList() {
  saleDetailBySaleId({ orderId: props.saleOrderId }).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data
    }
  })
}
</script>
